package com.ganzalang.gmall.concurrentart.lock.synchronizer;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * @description: 独占锁
 * @author: Ganzalang
 * @Date 2021/7/8 16:32
 */
public class Mutex {

    public static class Sync extends AbstractQueuedSynchronizer {
        // 当状态为0时获取锁
        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0, 1)) {
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        // 释放锁，设置状态为0
        @Override
        protected boolean tryRelease(int arg) {
             if (getState() == 0) {
                 throw new IllegalMonitorStateException();
             }
             setExclusiveOwnerThread(null);
             setState(0);
            return true;
        }

        // 是否处于占用状态
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }
    }

    /**
     * 将操作代理到Sync上
     */
    private final Sync sync = new Sync();

     public void lock() {
         sync.acquire(1);
     }

     public void release() {
         sync.release(1);
     }
}
